import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Col, Form, Input, Row, Spin, Button, message, Select, DatePicker } from 'antd';
import React, { Ref, useEffect, useMemo, useRef, useCallback, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { getLoadMapList, getTenantID, onCloseModalCommon, commonDeptGetUser } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { addDelegateService, editDelegateService, getDelegateByIdService } from '../services';
import { getFlowOrgTreeByOrgIDService, getUserDataList } from '@/services/BaseLayout';
import MyIcon from '@/components/MyIcon';
import moment from 'moment';
import { UpdateAssignDept } from './UpdateAssignDept';
import { UpdateAgentDept } from './UpdateAgentDept';

const { RangePicker }: any = DatePicker;

export const UpdateViewModal: React.FC<DelegateManageAPI.IUpdateViewModal> = ({ onClose, checkRowsInfo, reloadManage, curRes }) => {
  /** 弹框Ref */
  const updateDeleGateModalRef: Ref<IOneModalRef> = useRef(null);

  /**保存上级岗位搜索输入框的值*/
  const [treeSearch, setTreeSearch] = useState<string>('');

  /**保存委托人，代理人ID */
  const [userID, setUserID] = useState<Record<string, any>>({
    assignUserID: '',
    agentUserID: '',
  });

  /** form表单实例 */
  const [updateForm] = Form.useForm();

  /** 获取数据字典loadMdicMap */
  const { loadMapInfo, mapLoading }: Record<string, any> = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}`, //流程类别
  ]);

  /** 关闭弹框 */
  const onCloseModal = () => {
    onCloseModalCommon(updateDeleGateModalRef);
  };

  /** 详情接口回调 */
  const detailCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      updateForm?.setFieldsValue({
        ...res?.obj,
      });
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情接口 */
  const { getDelegateByIdInfo, getDelegateByIdLoading, getDelegateByIdRun } = getDelegateByIdService(detailCallback);

  /** 添加编辑弹框 */
  const updateCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadManage();
      onCloseModalCommon(updateDeleGateModalRef);
    } else {
      message.error(res?.msg);
    }
  };

  /** 添加接口 */
  const { addDelegateRun, addDelegateLoading } = addDelegateService(updateCallback);

  /** 编辑接口 */
  const { editDelegateLoading, editDelegateRun } = editDelegateService(updateCallback);

  /**
   * 保存按钮
   */
  const onSave = () => {
    updateForm?.validateFields()?.then((values: any) => {
      let [startTime, endTime]: any = values?.delegateTime;
      let time = {
        startTime: startTime.format('YYYY-MM-DD 00:00:00'),
        endTime: endTime.format('YYYY-MM-DD 23:59:59'),
      };

      const payload: Record<string, any> = {
        ...values,
        ...time,
      };

      delete payload?.delegateTime;

      //添加编辑
      if (checkRowsInfo?.id) {
        const editPayload: Record<string, any> = {
          ...payload,
          id: getDelegateByIdInfo?.id,
          isOpen: getDelegateByIdInfo?.isOpen,
          versionNum: getDelegateByIdInfo?.versionNum,
        };
        editDelegateRun(editPayload);
      } else {
        const addPayload: Record<string, any> = {
          ...payload,
          isOpen: 1,
        };
        addDelegateRun(addPayload);
      }
    });
  };

  /** 初始化 */
  useEffect(() => {
    if (checkRowsInfo && checkRowsInfo?.id) {
      getDelegateByIdRun({
        id: checkRowsInfo?.id,
      });
    }
  }, [checkRowsInfo]);

  /**详情反显数据 */
  useEffect(() => {
    if (getDelegateByIdInfo && getDelegateByIdInfo?.id) {
      updateForm?.setFieldsValue({
        ...getDelegateByIdInfo,
        delegateTime: [moment(getDelegateByIdInfo?.startTime), moment(getDelegateByIdInfo?.endTime)],
      });
    }
  }, [getDelegateByIdInfo]);

  /** 弹框底部按钮 */
  const footerModal = useMemo(() => {
    return (
      <>
        <Button
          key="back"
          onClick={onCloseModal}
          // icon={<CloseCircleOutlined />}
        >
          {getDelegateByIdInfo?.id ? '取消' : '关闭'}
        </Button>
        {curRes['/delegateController/add'] && curRes['/delegateController/edit'] && (
          <Button
            key="submit"
            type="primary"
            loading={addDelegateLoading || editDelegateLoading || getDelegateByIdLoading}
            // icon={<SaveOutlined />}
            onClick={() => {
              onSave();
            }}
          >
            {getDelegateByIdInfo?.id ? '确认' : '保存'}
          </Button>
        )}
      </>
    );
  }, [curRes, addDelegateLoading, editDelegateLoading, getDelegateByIdLoading]);

  // 获取搜索框输入的值
  const treeSearchValue = useCallback(
    (valText: string) => {
      setTreeSearch(valText);
    },
    [treeSearch],
  );

  return (
    <OneModal
      open={true}
      ref={updateDeleGateModalRef}
      width={document.body.clientWidth * 0.35}
      title={checkRowsInfo?.id ? '编辑委托' : '添加委托'}
      onCancel={onClose}
      bodyStyle={{
        padding: '5px 10px',
      }}
      centered
      footer={footerModal}
      confirmLoading={addDelegateLoading || editDelegateLoading || getDelegateByIdLoading || mapLoading}
    >
      <Spin spinning={addDelegateLoading || editDelegateLoading || getDelegateByIdLoading || mapLoading}>
        <div className={pageStyles['fromView-styles']}>
          <Form form={updateForm}>
            <Row>
              <UpdateAssignDept
                formRef={updateForm}
                detailInfo={checkRowsInfo}
                treeSearch={treeSearch}
                treeSearchValue={treeSearchValue}
                agentUserID={userID.agentUserID}
                changeAssignUser={(data: string) => {
                  setUserID({
                    assignUserID: data,
                  });
                }}
              />

              <UpdateAgentDept
                formRef={updateForm}
                detailInfo={checkRowsInfo}
                treeSearch={treeSearch}
                treeSearchValue={treeSearchValue}
                assignUserID={userID.assignUserID}
                changeAgentUser={(data: string) => {
                  setUserID({
                    agentUserID: data,
                  });
                }}
              />

              <Col span={24}>
                <Form.Item
                  label="委托时间"
                  name="delegateTime"
                  rules={[
                    {
                      required: true,
                      message: '请选择委托时间',
                    },
                  ]}
                >
                  <RangePicker
                    style={{ width: '100%' }}
                    format="YYYY-MM-DD"
                    placeholder={['开始日期', '结束日期']}
                    ranges={{
                      今天: [moment(), moment()],
                      本周: [moment().startOf('week'), moment().endOf('week')],
                      本月: [moment().startOf('month'), moment().endOf('month')],
                      本年: [moment().startOf('year'), moment().endOf('year')],
                    }}
                  />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item
                  label="委托原因"
                  name="delegateReason"
                  rules={[
                    {
                      required: true,
                      message: '请输入委托原因',
                    },
                  ]}
                >
                  <Input.TextArea placeholder={`请输入委托原因`} showCount maxLength={200} autoSize={{ minRows: 3, maxRows: 6 }} />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item
                  label={'业务名称'}
                  name="category"
                  rules={[
                    {
                      required: true,
                      message: '请选择业务名称',
                    },
                  ]}
                >
                  <Select placeholder={`请选择业务名称`} allowClear={true} loading={mapLoading}>
                    {loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}`]?.map((item: any) => {
                      return (
                        <Select.Option key={item?.id} value={item?.id}>
                          <MyIcon style={{ marginRight: 5 }} type="cluster" />
                          {item?.name}
                        </Select.Option>
                      );
                    })}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item
                  label="备注"
                  name="remark"
                  rules={[
                    {
                      required: false,
                      message: '请输入备注',
                    },
                  ]}
                >
                  <Input.TextArea placeholder={`请输入备注`} showCount maxLength={200} autoSize={{ minRows: 2, maxRows: 6 }} />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
      </Spin>
    </OneModal>
  );
};
